package com.usian.controller;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.usian.Result;
import org.apache.commons.lang.StringUtils;
import org.aspectj.weaver.ast.Var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;


@RequestMapping("/file")
@RestController
public class FileUploadController {

    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    private static final List<String> CONTENT_TYPES = Arrays.asList("image/jpeg","image/jpg","image/png","image/gif");

    @RequestMapping("upload")
    private Result upload(MultipartFile file){
        String originalFilename = file.getOriginalFilename();
//        校验文件的类型
        try {
            String contentType = file.getContentType();
            if (!CONTENT_TYPES.contains(contentType)) {
    //            文件类型不合法，直接返回
                return Result.error("文件类型不合法"+originalFilename);
            }
            BufferedImage read = ImageIO.read(file.getInputStream());
            if (read==null) {
                return Result.error("文件不合法"+originalFilename);
            }

            String name = StringUtils.substringAfterLast(originalFilename, ".");

            StorePath storePath = fastFileStorageClient.uploadFile(file.getInputStream(), file.getSize(), name, null);
            return Result.ok("http://image.usian.com/"+storePath.getFullPath());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.error("上传失败");
    }
}
